package com.hui.platform.falseworkapi.service.base.oss.service.impl;


import com.hui.platform.falseworkapi.service.base.oss.constant.OssDirEnum;
import com.hui.platform.falseworkapi.service.base.oss.dto.PreSaveFile;
import com.hui.platform.falseworkapi.service.base.oss.service.FileService;
import com.hui.platform.falseworkapi.service.base.oss.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.*;

@Service
@Transactional
public class FileServiceImpl implements FileService {
  
    @Autowired
    private OssService ossService;

    @Override
    public Map<String, Object> uploadFile( List<MultipartFile> file) {
        Map<String, Object> result = new HashMap<>();
        result.put("statusCode", "success");
        try {
            List<PreSaveFile> preSaveFileList = new ArrayList<>();
            //单文件
            for (MultipartFile f : file) {
                PreSaveFile sellerPreData = new PreSaveFile();
                String fileName = f.getOriginalFilename();
                //临时处理，如果文件名是以https://xxxx开头表明以及上传过了
                String path;
                if(Optional.ofNullable(fileName).orElse("").startsWith("https://")){
                   path=fileName;
                   fileName=f.getName();//设置文件名
                }else{
                    path = ossService.uploadFile(fileName, f.getInputStream(), OssDirEnum.FILE_DIR);
                }
                //------
                sellerPreData.setTitle(fileName);
                sellerPreData.setUrl(path);
                sellerPreData.setSize(new BigDecimal(f.getSize()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                preSaveFileList.add(sellerPreData);
            }
            result.put("preSaveFileList",preSaveFileList);
            return result;
        }catch (Exception e) {
            e.printStackTrace();
            result.put("statusCode","fail");
            result.put("message","上传失败");
            return result;
        }
    }

    /**
     * MulipartFile 转 File
     * @param multipartFile
     * @return
     * @throws Exception
     */
    public File mulipartFileToFile(MultipartFile multipartFile)throws Exception{
        File toFile = null;
        if(!multipartFile.equals("") && multipartFile.getSize() > 0){
            InputStream ins = null;
            ins = multipartFile.getInputStream();
            toFile = new File(multipartFile.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    public  void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param watermarkList 水印内容
     * @param markContentColor 水印颜色
     * @param font 水印字体
     */
    public File addWaterMark(File srcImgFile, List<Map<String,Object>> watermarkList, Color markContentColor, Font font) {
        try {
            // 读取原图片信息
            BufferedImage srcImg = ImageIO.read(srcImgFile);//文件转化为图片
            int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
            int srcImgHeight = srcImg.getHeight(null);//获取图片的高
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            g.setColor(markContentColor); //根据图片的背景设置水印颜色
            g.setFont(font);              //设置字体
            g.drawString("版权信息", 500, 300);  //画出水印
            //支持多水印
            if(watermarkList != null){
                for(Map<String,Object> map : watermarkList){
                    String content = (String)map.get("content");
                    int x = (int)map.get("x");
                    int y = (int)map.get("y");
                    g.drawString(content, x, y);  //画出水印
                }
            }
            g.dispose();
            ImageIO.write(bufImg,"jpeg",srcImgFile);
            return srcImgFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return srcImgFile;
    }

}
